package com.wit.health.UI;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.wit.health.R;
import com.wit.health.decorator.AspectRatioVideoView;

public class ExerciseDetailActivity extends AppCompatActivity {

    private  final static  String TAG = "ExerciseDetailActivity";

    private AspectRatioVideoView videoView;
    private TextView tvDescription;
    private Button btnStart;
    private TextView tvExercise;
    private ImageButton playPauseButton;
    private SeekBar progressSeekBar;

    private TextView currentTimeTextView;

    private TextView totalTimeTextView;

    private Handler handler = new Handler();
    private Runnable hidePlayPauseButtonRunnable = new Runnable() {
        @Override
        public void run() {
            playPauseButton.setVisibility(View.GONE);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise_detail);

        // 获取传递过来的数据
        Intent intent = getIntent();
        String exerciseName = intent.getStringExtra("exerciseName");
        String exerciseVideoUrl = intent.getStringExtra("exerciseVideoUrl");
        String exerciseDescription = intent.getStringExtra("exerciseDescription");

        playPauseButton = findViewById(R.id.playPauseButton);

        progressSeekBar = findViewById(R.id.progressSeekBar);

        tvExercise = findViewById(R.id.exerciseNameTextView);

        tvExercise.setText(exerciseName);

        videoView = findViewById(R.id.video_view);

        currentTimeTextView = findViewById(R.id.currentTimeTextView);

        totalTimeTextView = findViewById(R.id.totalTimeTextView);

        int videoResourceId = intent.getIntExtra("exerciseVideoResourceId", 0);
        Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + videoResourceId);
        videoView.setVideoURI(videoUri);
        videoView.requestFocus();

        // 设置播放/暂停按钮点击事件
        playPauseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoView.isPlaying()) {
                    videoView.pause();
                    playPauseButton.setImageResource(R.drawable.ic_play);
                } else {
                    videoView.start();
                    playPauseButton.setImageResource(R.drawable.ic_pause);
                }
                showPlayPauseButton();
            }
        });

        videoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPlayPauseButton();
            }
        });


        // 设置进度条更新逻辑
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {

                int videoWidth = mediaPlayer.getVideoWidth();
                int videoHeight = mediaPlayer.getVideoHeight();
                float videoAspectRatio = (float) videoWidth / videoHeight;
                videoView.setAspectRatio(videoAspectRatio);

                Log.d(TAG, "videoWidth: " + videoWidth + "videoHeight: " + videoHeight);


                int duration = videoView.getDuration();
                progressSeekBar.setMax(duration);
                totalTimeTextView.setText(formatTime(duration));
                progressSeekBar.postDelayed(onEverySecond, 1000);
            }
        });

        progressSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    videoView.seekTo(progress);
                }
                currentTimeTextView.setText(formatTime(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 开始拖动进度条时暂停视频
                videoView.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖动进度条时恢复视频播放
                videoView.start();
            }
        });

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                // 视频播放完毕后的处理逻辑
                playPauseButton.setImageResource(R.drawable.ic_play);
                videoView.seekTo(0); // 将视频进度重置为开始位置
                handler.removeCallbacks(hidePlayPauseButtonRunnable); // 取消延迟隐藏操作
                playPauseButton.setVisibility(View.GONE); // 立即隐藏图标
            }
        });

        tvDescription = findViewById(R.id.tv_description);
        tvDescription.setText(exerciseDescription);
        btnStart = findViewById(R.id.btn_start);
    }

    private Runnable onEverySecond = new Runnable() {
        @Override
        public void run() {
            if (progressSeekBar != null && videoView != null) {
                // progressSeekBar.setProgress(videoView.getCurrentPosition());
                int currentPosition = videoView.getCurrentPosition();
                progressSeekBar.setProgress(currentPosition);
//                progressSeekBar.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        progressSeekBar.setProgress(videoView.getCurrentPosition());
//                    }
//                });
                Log.d(TAG, "Current position: " + currentPosition);
                currentTimeTextView.setText(formatTime(currentPosition));
//                if (videoView.isPlaying()) {
//                    Log.d(TAG, "videoView is playing" + videoView.isPlaying());
//                    progressSeekBar.postDelayed(onEverySecond, 1000);
//                }

                if (currentPosition < videoView.getDuration()) {
                    progressSeekBar.postDelayed(onEverySecond, 1000);
                }

            }

        }
    };

    private void showPlayPauseButton() {
        playPauseButton.setVisibility(View.VISIBLE);
        handler.removeCallbacks(hidePlayPauseButtonRunnable);
        handler.postDelayed(hidePlayPauseButtonRunnable, 2000); // 延迟 2 秒后隐藏图标
    }

    private String formatTime(int milliseconds) {
        int seconds = (milliseconds / 1000) % 60;
        int minutes = (milliseconds / (1000 * 60)) % 60;
        int hours = (milliseconds / (1000 * 60 * 60)) % 24;

        if (hours == 0) {
            return String.format("%02d:%02d", minutes, seconds);
        } else {
            return String.format("%02d:%02d:%02d", hours, minutes, seconds);
        }
    }
}